package com.si.anddos.library.main;

import java.io.File;
import java.util.ArrayList;

import com.si.anddos.R;
import com.si.anddos.UploadProviderService;
import com.si.anddos.dpadapters.AnddosDbAdapter;
import com.si.anddos.dpadapters.DatabaseProvider;
import com.si.anddos.dpadapters.Upload;
import com.si.anddos.library.main.factory.ServiceProviderFactory;
import com.si.anddos.library.provider.ProviderMessage;
import com.si.anddos.library.provider.ServiceProvider;

public class UploadProviderThread extends Thread {

	private UploadProviderService ups;
	private DatabaseProvider dbProvider;
	private ArrayList<Upload> uploads;

	public UploadProviderThread(DatabaseProvider db, UploadProviderService ups) {
		this.dbProvider = db;
		this.ups = ups;
	}

	/**
	 * function controls database for new not opened uploads and upload it
	 */
	private void upload() {
		this.dbProvider.open();
		for (Upload u : this.uploads) {
			this.dbProvider.updateStatusUpload(u.getId(),
					AnddosDbAdapter.StatusProcessing);
			ServiceProvider udp = ServiceProviderFactory
					.getUploadProvider("rapidshare");
			File f = new File(u.getFilePath());

			ProviderMessage pm = new ProviderMessage(this.ups.getText(
					R.string.uploadServiceFinished).toString()
					+ " " + u.getFileName(), this.ups);
			udp.upload(f, u.getAccount());
			this.dbProvider.updateStatusUpload(u.getId(),
					AnddosDbAdapter.StatusDone);
			pm.showMessage();
		}

		this.reloadUploads();
	}

	private void reloadUploads() {
		this.dbProvider.open();
		this.uploads = this.dbProvider.getAllWaitingUploads();
		this.dbProvider.close();

		if (this.uploads.isEmpty()) {
			this.ups.stopSelf();
		} else {
			this.upload();
		}
	}

	public void run() {
		this.reloadUploads();
	}
}
